package com.sunny.ynhz.ui.patrol;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.google.gson.Gson;
import com.sunny.ynhz.R;
import com.sunny.ynhz.ui.base.AppBaseTitleBarActivity;
import com.sunny.ynhz.bean.LocationBean;
import com.sunny.ynhz.bean.PatrolStatusBean;
import com.sunny.ynhz.api.HttpManager;
import com.sunny.ynhz.api.subscriber.ApiSubscriber;

import java.util.LinkedList;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by luao on 2017/7/12.
 * <p>
 * 巡河轨迹页面
 */
public class PatrolPathActivity extends AppBaseTitleBarActivity implements AMap.OnMapClickListener, LocationSource,
        AMapLocationListener {
    @BindView(R.id.patrol_path_map)
    MapView patrolPathMap;
    private AMap aMap;

    /**
     * 定位点数组
     */
    LinkedList<LatLng> latLngList;
    /**
     * 巡河轨迹点list2
     */
    LinkedList<LocationBean> pathList;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private Marker marker;
    private Polygon polygon;
    private OnLocationChangedListener mListener;
    private boolean mFirstFix = false;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    private Circle mCircle;
    private Marker mLocMarker;
    public static final String LOCATION_MARKER_FLAG = "mylocation";
    /**
     * 是否是第一次定位
     */
    private boolean isFirstLocation = true;
    private Polyline polyLine;
    /**
     * 是否上报
     */
    private boolean isUpLoadPosition = false;
    /**
     * 用户id
     */
    private String userId;
    /**
     * 巡河id  用户id + 开始时刻的时间戳
     */
    private String patrolId;
    /**
     * 定位信息json
     */
    private String json;
    private boolean isStartPatrol = false;
    private Gson gson;
    private boolean isFirstUploadPostion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_patrol_path);
        ButterKnife.bind(this);
        gson = new Gson();
        patrolPathMap.onCreate(savedInstanceState);// 此方法必须重写
        aMap = patrolPathMap.getMap();
        aMap.setOnMapClickListener(this);
        drawRect();
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        setUpLocation();

    }


    private void drawRect() {
        //绘制区域
        PolygonOptions pOption = new PolygonOptions();
        pOption.add(new LatLng(23.146943, 113.342913));
        pOption.add(new LatLng(23.14572, 113.341776));
        pOption.add(new LatLng(23.144655, 113.34375));
        pOption.add(new LatLng(23.14499, 113.345746));
        pOption.add(new LatLng(23.146785, 113.345488));
        polygon = aMap.addPolygon(pOption.strokeWidth(4)
                .strokeColor(Color.argb(50, 1, 1, 1))
                .fillColor(Color.argb(50, 1, 1, 1)));
    }

    private void setUpLocation() {
        pathList = new LinkedList<LocationBean>();
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(3000);//设置定位间隔,单位毫秒,默认为2000ms
            //设置定位参数

            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        }
        mlocationClient.startLocation();
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    private void setPath(LinkedList<LatLng> linkedList) {
        polyLine = aMap.addPolyline(new PolylineOptions().
                addAll(linkedList).width(10).color(Color.argb(255, 1, 1, 1)));
    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (marker != null) {
            marker.remove();
        }
        marker = aMap.addMarker(new MarkerOptions().position(latLng));
        boolean b1 = polygon.contains(latLng);
        Toast.makeText(this, "是否在围栏里面：" + b1, Toast.LENGTH_SHORT).show();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        patrolPathMap.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        patrolPathMap.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        patrolPathMap.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        patrolPathMap.onDestroy();

    }

    private void startPatrol() {
        isStartPatrol = true;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.e("hu",aMapLocation.getAddress());
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                LatLng location = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                if (!mFirstFix) {
                    mFirstFix = true;
                    addCircle(location, aMapLocation.getAccuracy());//添加定位精度圆
                    addMarker(location);//添加定位图标
//                    mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                } else {
                    mCircle.setCenter(location);
                    mCircle.setRadius(aMapLocation.getAccuracy());
                    mLocMarker.setPosition(location);
                }
                if (isFirstLocation) {
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));
                    isFirstLocation = false;
                }
                //判断定位信息是否在围栏里，是就可以巡河，不是就不可以巡河
                LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                boolean b1 = polygon.contains(latLng);
                if (b1) {
                    //可以巡河
                } else {
                    //不能巡河
                }
                //轮询服务器状态  拿一个是否需要 发送数据
                //生成巡河id  用户+id+毫秒
                //是否开始巡河，开始巡河，开始记录轨迹
                if (isStartPatrol) {
                    latLngList.add(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
                    String timeStr = "123";
                    pathList.add(new LocationBean());

                    json = gson.toJson(pathList);
                }
                //是否上传
                if (isUpLoadPosition) {
                    patrolId = userId + String.valueOf(System.currentTimeMillis());
                    //是否第一上传，第一次就传所有的信息,不是第一次，就传最后一个点
                    if (isFirstUploadPostion) {
                        uploadPosition(patrolId, userId, json);
                    } else {
                        pathList.clear();
                        String timeStr = "123";
                        pathList.add(new LocationBean());
                        uploadPosition(patrolId, userId, json);
                    }
                } else {
                    getStatus();
                }

                setPath(latLngList);

            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    private void uploadPosition(String patrolId, String userId, String json) {

    }

    /**
     * 上传巡河信息
     */
    public void getStatus() {
        HttpManager.getInstance()
                .getPatrolStatus()
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiSubscriber(this, new ApiSubscriber.HttpOnResultListener<PatrolStatusBean>() {
                    @Override
                    public void onNext(PatrolStatusBean jsonObject) {
                        // TODO: 2017/7/13 判断userid是否等于本地登陆的userid
                        if (!jsonObject.getUserId().equals("")) {
                            isUpLoadPosition = true;
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onstart() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("HTTP", "" + e.getMessage() + e.toString());
                    }
                }));
    }


    private void addCircle(LatLng latlng, double radius) {
        CircleOptions options = new CircleOptions();
        options.strokeWidth(1f);
        options.fillColor(FILL_COLOR);
        options.strokeColor(STROKE_COLOR);
        options.center(latlng);
        options.radius(radius);
        mCircle = aMap.addCircle(options);
    }

    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {
            return;
        }
        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.statistics_icon);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
        mLocMarker.setTitle(LOCATION_MARKER_FLAG);
    }
}
